<?php

namespace app\system\controller;

use app\system\service\AuthService;
use app\system\service\Token;
use app\system\service\TokenService;
use think\Request;
use think\Validate;

class Auth extends Validate
{
    protected $authService;

    public function __construct(AuthService $authService)
    {
        $this->authService = $authService;
    }

    /**
     * 描述:登录
     * 参数:{}
     * 返回:
     * 作者:W
     */
    public function login(Request $request)
    {
        $data = [
            'username' => $request->post('username'),
            'password' => $request->post('password'),
        ];

        return $this->authService->login($data);
    }

    /**
     * 描述:刷新token
     * 参数:{}
     * 返回:
     * 作者:W
     */
    public function refreshToken(Request $request)
    {
        try {
            // 从请求头或者其他地方获取刷新令牌
            $refreshToken = $request->post('refreshToken');
            // 检查刷新令牌是否存在
            if (!$refreshToken) {
                return json([
                    'success' => false,
                    'message' => '令牌不存在!'
                ]);
            }

            // 调用 TokenService 来刷新令牌
            $newToken = (new TokenService())->refreshToken($refreshToken);

            // 如果刷新成功，返回新的访问令牌
            return json([
                'success' => true,
                'data' => [
                    'accessToken' => $newToken['accessToken'],
                    'refreshToken' => $newToken['refreshToken'], // 也可以选择不更新刷新令牌
                    'expires' => $newToken['expires'],
                    'message' => '令牌刷新成功'
                ]
            ]);
        } catch (Exception $e) {
            // 如果有任何错误发生（如令牌无效或已过期），返回错误信息
            return json([
                'success' => false,
                'message' => $e->getMessage()
            ], $e->getCode());
        }
    }

}
